package com.inossem.emergency.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.inossem.emergency.R;
import com.inossem.emergency.activity.bluetooth.BlueToothBaseActivity;
import com.inossem.emergency.activity.bluetooth.BluetoothListActivity;
import com.inossem.emergency.adapter.EmergencyDetailAdapter;
import com.inossem.emergency.api.ApiService;
import com.inossem.emergency.constant.ItemStatusConstant;
import com.inossem.emergency.constant.UrlConstant;
import com.inossem.emergency.db.CacheBean;
import com.inossem.emergency.utils.ACacheUtils;
import com.inossem.emergency.utils.DialogUtils;
import com.inossem.emergency.utils.GreenDaoManager;
import com.inossem.emergency.utils.TimeUtils;
import com.inossem.emergency.utils.ToastUtils;
import com.inossem.emergency.utils.Utils;
import com.inossem.emergency.utils.requestUtils.InossemNewsCallback;
import com.inossem.emergency.utils.requestUtils.RetrofitUtils;
import com.inossem.wms.model.cus.CusRFID;
import com.inossem.wms.vo.BaseObject;
import com.inossem.wms.vo.auth.SysLoginVo;
import com.inossem.wms.vo.auth.SysResourcesVo;
import com.inossem.wms.vo.cus.CusRFIDEmergency;
import com.inossem.wms.vo.cus.CusRFIDTaskReqVo;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Response;

public class EmergencyDetailActivity extends BlueToothBaseActivity {

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R.id.tv_information)
    TextView mTvInformation;
    @BindView(R.id.tv_return)
    TextView mTvReturn;
    @BindView(R.id.tv_add)
    TextView mTvAdd;
    @BindView(R.id.include_no_data)
    LinearLayout includeNoData;
    private ScanBroadcastReceiver mBroadcastReceiver;
    //是否可以扫码
    private boolean isCanLoad = true;
    //是否有网络
    private boolean isNetWork = false;
    private int mType;
    private String mWhCode;
    private String mWhName;
    private Integer mReceiptType;
    private String mReceiptTypeName;
    private List<CacheBean> mCacheBeanList;
    private List<CusRFIDTaskReqVo> mList = new ArrayList<>();
    //物料信息
    private CusRFIDEmergency mCusRFID;
    //单据实体
    private CacheBean mCacheBean;
    private GreenDaoManager mGreenDaoManager;
    private EmergencyDetailAdapter mAdapter;
    private boolean isEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_emergency_detail);
        ButterKnife.bind(this);
        initData();
    }

    public void initData() {
        //默认不弹出键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        //强制横屏z
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        mType = getIntent().getIntExtra(ItemStatusConstant.STATUS_CODE, ItemStatusConstant.STATUS_CREATE);
        mWhCode = getIntent().getStringExtra(ItemStatusConstant.CUS_WH_SYS);
        mWhName = getIntent().getStringExtra(ItemStatusConstant.CUS_WH_NAME);
        mReceiptTypeName = getIntent().getStringExtra(ItemStatusConstant.RECEIPT_TYPE_NAME);
        mReceiptType = getIntent().getIntExtra(ItemStatusConstant.RECEIPT_TYPE, ItemStatusConstant.STATUS_CREATE);
        GreenDaoManager.getInstance().init(EmergencyDetailActivity.this);
        mGreenDaoManager = GreenDaoManager.getInstance();
        mCacheBeanList = mGreenDaoManager.getCacheBeanList();
        mBroadcastReceiver = new ScanBroadcastReceiver();
        LinearLayoutManager manager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(manager);
//        Utils.isNetWorkAvailableOfGet(UrlConstant.DEFAULT_HTTP, new Comparable<Boolean>() {
        Utils.isNetWorkAvailableOfGet(UrlConstant.DEFAULT_HTTP + UrlConstant.DEFAULT_DOMAIN + ":" + UrlConstant.DEFAULT_PORT + UrlConstant.DEFAULT_PATH, new Comparable<Boolean>() {
            @Override
            public int compareTo(Boolean available) {
                isNetWork = available;
                if (available) {
                    ToastUtils.showToast("有网络");
                } else {
                    ToastUtils.showToast("没有网络");
                }
                return 0;
            }
        });
        if (mType == ItemStatusConstant.STATUS_CREATE) {
            isEdit = true;
            mAdapter = new EmergencyDetailAdapter(this, isEdit);
            mRecyclerView.setAdapter(mAdapter);
            //初始化列表信息
            mCacheBean = new CacheBean();
            if (mCacheBeanList.size() == 0) {
                mCacheBean.setReceiptCode("10000001");
            } else {
                mCacheBean.setReceiptCode(Integer.valueOf(mCacheBeanList.get(mCacheBeanList.size() - 1).getReceiptCode()) + 1 + "");
            }
            mCacheBean.setReceiptType(mReceiptType);
            mCacheBean.setReceiptTypeName(mReceiptTypeName);
            mCacheBean.setWhCode(mWhCode);
            mCacheBean.setWhName(mWhName);
            setBuletoothScan(/*"AA:A8:AC:04:51:51" ,*/ result -> {
                scanRfid(result);
            });
            mTvAdd.setText("添加");
        } else if (mType == ItemStatusConstant.STATUS_COMPLETED) {
            mTvAdd.setText("查看签字");
            isEdit = false;
            mAdapter = new EmergencyDetailAdapter(this, isEdit);
            mRecyclerView.setAdapter(mAdapter);
            mCacheBean = (CacheBean) getIntent().getSerializableExtra(ItemStatusConstant.DATA);
            mAdapter.clearList();
            mList = new Gson().fromJson(mCacheBean.getJsonList(), new TypeToken<List<CusRFIDTaskReqVo>>() {
            }.getType());
            mAdapter.addList(mList);
            mTvInformation.setText(mList.size() + "");
            showNoData();
        }
        mAdapter.setListener(new EmergencyDetailAdapter.OnItemClickListener() {
            @Override
            public void onDetailClick(int position) {
                DialogUtils.getRemarkDialog(EmergencyDetailActivity.this, mList.get(position).getLocationCode(), isEdit, new DialogUtils.OnRemarkClickListener() {
                    @Override
                    public void onClickListener(String title) {
                        mList.get(position).setLocationCode(title);
                    }
                }).show();
            }
        });
    }

    //识别到rfid处理
    private void scanRfid(String result) {
        if (isCanLoad) {
            result = result.trim();
            if (TextUtils.isEmpty(result)) {
                return;
            }
            isCanLoad = false;
            ToastUtils.showToast(result);
            boolean isHave = false;
            for (CusRFIDTaskReqVo bean : mList) {
                if (bean.getEpcCode().equalsIgnoreCase(result)) {
                    isHave = true;
                    break;
                }
            }
            if (!isHave) {
                if (isNetWork) {
                    //获取物料信息
                    getRfid(result);
                } else {
                    CusRFIDEmergency cusRFID = new CusRFIDEmergency();
                    cusRFID.setEpcCode(result);
                    cusRFID.setQty(BigDecimal.valueOf(0));
                    initMat(cusRFID);
                }
            } else {
                isCanLoad = true;
                ToastUtils.showToast("改物料已存在");
            }
        }
    }

    //通过rifd获取物料信息
    private void getRfid(String rfid) {
        RetrofitUtils.getRetrofit(EmergencyDetailActivity.this, "", "", "", "物料查询")
                .create(ApiService.class)
                .getRFIDType(rfid)
                .enqueue(new InossemNewsCallback<BaseObject<CusRFIDEmergency>>() {
                    @Override
                    public void success(Response<BaseObject<CusRFIDEmergency>> response) {
                        // 10 物料
                        // 20 仓位
                        // 30 存储单元
                        mCusRFID = response.body().getData();
                        if (mCusRFID == null) {
                            mCusRFID = new CusRFIDEmergency();
                            mCusRFID.setEpcCode(rfid);
                            mCusRFID.setQty(BigDecimal.valueOf(0));
                        }
                        initMat(mCusRFID);
                        isCanLoad = true;
                    }

                    @Override
                    public void failure(Response<BaseObject<CusRFIDEmergency>> response) {
                        ToastUtils.showToast(response.body().getReturnMsg());
                        isCanLoad = true;
                    }
                });
    }

    //生成物料信息
    private void initMat(CusRFIDEmergency cusRFID) {
        //初始化详情信息
        CusRFIDTaskReqVo cusRFIDTaskReqVo = new CusRFIDTaskReqVo();
        cusRFIDTaskReqVo.setEpcCode(cusRFID.getEpcCode());
        cusRFIDTaskReqVo.setMatCode(cusRFID.getMatCode());
        cusRFIDTaskReqVo.setMatName(cusRFID.getMatName());
        cusRFIDTaskReqVo.setBatch(cusRFID.getBatch());
        cusRFIDTaskReqVo.setQty(BigDecimal.valueOf(0));
        cusRFIDTaskReqVo.setWhCode(mCacheBean.getWhCode());
        cusRFIDTaskReqVo.setWhReal(mCacheBean.getWhName());
        cusRFIDTaskReqVo.setReceiptCode(mCacheBean.getReceiptCode());
        cusRFIDTaskReqVo.setReceiptType(mCacheBean.getReceiptType());
        cusRFIDTaskReqVo.setReceiptTypeName(mCacheBean.getReceiptTypeName());
        mList.add(cusRFIDTaskReqVo);
        mTvInformation.setText(mList.size() + "");
        mAdapter.clearList();
        mAdapter.addList(mList);
        showNoData();
        isCanLoad = true;
    }

    public class ScanBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals("com.symbol.datawedge.DWDEMO")) {
                //扫码
                scanRfid(intent.getStringExtra("com.symbol.datawedge.data_string"));
            }
            if (intent.getAction().equals("scanner_receiver")) {
                //扫码
                scanRfid(intent.getStringExtra("scanner_receiver_data"));
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.symbol.datawedge.DWDEMO");           //  DW 6.x
        intentFilter.addAction("scanner_receiver");           //  DW 6.x
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);    //  NOTE: this IS REQUIRED for DW6.2 and up!
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    public void onPause() {
        super.onPause();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void showNoData() {
        if (mAdapter.getItemCount() <= 0) {
            includeNoData.setVisibility(View.VISIBLE);
            mRecyclerView.setVisibility(View.GONE);
        } else {
            includeNoData.setVisibility(View.GONE);
            mRecyclerView.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.tv_return, R.id.tv_add, R.id.settingImg})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_return:
                finish();
                break;
            case R.id.tv_add:
                if (mType == ItemStatusConstant.STATUS_CREATE) {
                    if (mList == null || mList.size() == 0) {
                        return;
                    }
                    DialogUtils.getSignDialog(EmergencyDetailActivity.this, new DialogUtils.OnSignClickListener() {
                        @Override
                        public void onClickListener(String title, String sign) {
                            if (mList.size() == 0) {
                                return;
                            }
                            mCacheBean.setRemark(title);
                            mCacheBean.setSignName(sign);
                            mCacheBean.setFileName("点击生成文件");
                            mCacheBean.setCreateTime(TimeUtils.getNowTime("-"));
                            mCacheBean.setJsonList(new Gson().toJson(mList));
                            mGreenDaoManager.addCacheBean(mCacheBean);
                            ToastUtils.showToast("添加成功");
                            finish();
                        }
                    }).show();
                } else if (mType == ItemStatusConstant.STATUS_COMPLETED) {
                    DialogUtils.checkSignDialog(EmergencyDetailActivity.this, mCacheBean).show();
                }
                break;
            case R.id.settingImg:
                startActivity(new Intent(EmergencyDetailActivity.this, BluetoothListActivity.class));
                break;
        }
    }
}
